var D = {} || window.D;
D.debug = false;
D.namespace = function() {
    var a = arguments,
    o = null,
    i, j, d;
    for (i = 0; i < a.length; ++i) {
        d = a[i].split(".");
        o = D;
        for (j = (d[0] === "D") ? 1 : 0; j < d.length; ++j) {
            o[d[j]] = o[d[j]] || {};
            o = o[d[j]];
        }
    }
    return o;
};
D.init = function(){
	for( func in D ){
		if ( typeof(D[func]) == 'object' && typeof(D[func]['init']) == 'function' ){
			try{
				D[func]['init']();
				console.log('[SECLog : DFunctions (D.' + func + '.init Success)]');
			}catch(e){
				if ( D.debug ){
					alert(e);
				}
//				console.log('[SECLog : DFunctions (D.' + func + '.init Error)]');
//				console.log('[SECLog : DFunctions (D.' + func + '.init Error is '+e+')]');
			}
		}
	}
}
D.function_exists = function(fn){
	return ( typeof(window[fn]) == 'function' ) ? true : false;
}
D.Call = function(fn){
	var args = Array.prototype.slice.apply(arguments);
	args.shift();
	if ( D.function_exists(fn) ){
		return window[fn].apply(this, args); 
	}
}
D.str_replace = function(search, replace, str){
	var regex = new RegExp(search, "g");
	return str.replace(regex, replace);
}
D.redirect = function(url, _blank){
	if ( _blank ){
		window.open(url);
	}else{
		window.location.href = url;
	}
}
D.explode = function(spearator, string, limit){
	return string.split(spearator, limit);
};
D.print_r = function(theObj) {
    var retStr = '';
    if (typeof theObj == 'object') {
        retStr += '<div style="font-family:Tahoma; font-size:7pt;">';
        for (var p in theObj) {
            if (typeof theObj[p] == 'object') {
                retStr += '<div><b>['+p+'] => ' + typeof(theObj) + '</b></div>';
                retStr += '<div style="padding-left:25px;">' + D.print_r(theObj[p]) + '</div>';
            } else {
                retStr += '<div>['+p+'] => <b>' + theObj[p] + '</b></div>';
            }
        }
        retStr += '</div>';
    }
    return retStr;
}
D.ie = function() {
    return /msie (\d+\.\d+)/i.test(navigator.userAgent) ? RegExp.$1 : undefined;
}();

D.strpos = function(haystack, needle, offset) {
	var i = (haystack + '').indexOf(needle, (offset || 0));
	return i === -1 ? false : i;
}

D.Core = {
	init : function(){
		$('.ajaxlink').on('click', function(){
			var box = $(this);
			var href = box.attr('href');
			var ask = box.attr('ask');
			if ( ask ){
				bootbox.confirm(ask, function(result){
					if( result ){
						D.ajax.get(href);
					}
				});
			}else{
				D.ajax.get(href);
			}
			return false;
		});
	}
}

D.T = {
	dom : function(dom, data, def){
		return this.include(dom.html(), data, def);
	},
	selector : function(selector, data, def){
		return this.dom($(selector), data, def);
	},
	include : function(template, data, def) {
		if ( !template || !data ){
			return null;
		}
		return template.replace(/\{([\w\.]*)\}/g,
		function(str, key) {
			var keys = key.split("."),
			v = data[keys.shift()];
			for (var i = 0, l = keys.length; i < l; i++) {
				v = v[keys[i]] ? v[keys[i]] : (def ? def : '');
			}
			return (typeof v !== "undefined" && v !== null) ? v: "";
		});
	},
	art : function(id, data){
		if( D.function_exists('template') ){
			return template.render(id, data);
		}
		console.log('ART -- TEMPLATE -- NOT LOAD');
		return null;
	}
}

D.UI = {
	initialize : false,
	init : function(){
		this.Widget();
		this.initialize = true;
	},
	Widget : function(){
		var widgets = $('.ui-widget-view');
		$.each(widgets, function(i, n){
			var widget = $(this);
			var config = eval('(' + widget.attr('config') + ')');
			config = config ? config : {};
			D.UI.position(widget, config);
		});
	},
	position : function(widget, config){
		var box = widget.parent() ? widget.parent() : $('.ui-main-view');
		var main = box.hasClass('ui-main-view');
		var lf = main ? box.offset().left : 0;
		var tp = main ? box.offset().top : 0;
		var data = {};
		data.position = config.position ? config.position : 'absolute';
		if( typeof(config.width) != 'undefined' ){
			if ( D.strpos(config.width, '%') ){
				config.width = parseInt(D.str_replace('%', '', config.width));
				data.width = box.width() * (config.width / 100);
			}else{
				data.width = config.width;
			}
		}
		if( typeof(config.index) != 'undefined' ){
			data['z-index'] = config.index;
		}

		if( typeof(config.height) != 'undefined' ){
			data.height = config.height;
		}

		if( typeof(config.top) != 'undefined' ){
			data.top = tp + config.top;
		}else if( typeof(config.bottom) != 'undefined' ){
			data.bottom = config.bottom;
		}

		if( typeof(config.left) != 'undefined' ){
			data.left = lf + config.left;
		}else if( typeof(config.bottom) != 'undefined' ){
			data.bottom = config.bottom;
		}

		if( typeof(config.right) != 'undefined' ){
			data.right = lf + config.right;
		}else if( typeof(config.l) != 'undefined' ){
			data.left = lf + config.left;
		}
		widget.css(data);
		if( config.callback && !this.initialize ){
			D.Call(config.callback);
		}
	}
}

D.ajax = {
	data : null,
	get : function(url, callback) {
		return this.call(url, 'GET', callback);
	},
	post : function(url, callback) {
		return this.call(url, 'POST', callback);
	},
	postdata : function(url, data, callback, async){
		this.data = data;
		return this.call(url, 'POST', callback, 'json', async);
	},
	call : function(url, method, callback, type, async){
		var data = this.data;
		method = method ? method : 'GET';
		type = type ? type : 'json';
		async = async ? async : true;
		$.ajax({
			url: url,
			type : method,
			data : data,
			dataType: type,
			async : async,
			success: callback ? callback : D.ajax.explain
		});
		return false;
	},
	explain : function(json){
		var type = json['type'];
		var data = json['data'];

		if ( type == 'alert' ) {
			bootbox.alert(data);
		} else if ( type == 'eval' ) { 
			eval(data);
		} else if ( type == 'refresh') {
			window.location.reload();
		} else if ( type == 'updater' ) {
			var id = data['id'];
			var inner = data['html'];
			$('#' + id).html(inner);
		} else if ( type == 'dialog' ) {
			bootbox.dialog({
				message: data
			});
		} else if ( type == 'mix' ) {
			for (var x in data) {
				json['data'] = data[x];
				D.ajax.explain(json);
			}
		}
	}
}

D.loading = {
	bootbox : function(){
		bootbox.alert('<div class="tree-loading" style="text-align: center;"><i class="icon-refresh icon-spin blue"></i></div>');
	}
}

D.Bug = {
	init : function(){
		var A, B;
		$(window).bind('keydown', function(event){
			var code = event.keyCode;
			if ( event.ctrlKey && event.altKey && code ){
				if ( code == 66 ){
					D.Bug.report();
				}
				return false;
			}
			if( code == 66 ){
				A = true;
			}
			if( code == 85 && A ){
				B = true;
				A = false;
			}
			if( code == 71 && B ){
				B = false;
				D.Bug.report();
			}
		});
	},
	report : function(){
		window.open('http://wpa.qq.com/msgrd?v=3&uin=2355561403&site=qq&menu=yes');
	}
}

$(D.init);